// 1.使用filter方法
let arr = [1, 1, 2, 2, 3, 3, 4, 5]

function removeDuplicates1 (data) {
    return data.filter((value, index) => data.indexOf(value) === index)
}

console.log(removeDuplicates1(arr)) // [ 1, 2, 3, 4, 5 ]

// 2.使用ES6的set
function removeDuplicates2 (data) {
    return [...new Set(data)] // 或 Array.from(new Set(data))
}

console.log(removeDuplicates2(arr)) // [ 1, 2, 3, 4, 5 ]

// 3.使用forEach方法
function removeDuplicates3 (data) {
    let unique = []
    data.forEach(item => {
        if (!unique.includes(item)) {
            unique.push(item)
        }
    })
    return unique
}

console.log(removeDuplicates3(arr)) // [ 1, 2, 3, 4, 5 ]

// 4.使用reduce方法
function removeDuplicates4 (data) {
    return data.reduce((a, b) => a.includes(b) ? a : [...a, b], [])
}

console.log(removeDuplicates4(arr)) // [ 1, 2, 3, 4, 5 ]

// 5.在数组原型链上添加去重方法
Array.prototype.unique = function () {
    let unique = []
    for (let i = 0; i < this.length; i++) {
        const current = this[i]
        if (!unique.includes(current)) unique.push(current)
    }
    return unique
}
console.log(arr.unique()) // [ 1, 2, 3, 4, 5 ]

// 6.重数组对象中删除重复对象
let users = [
    { id: 1, age: 1 },
    { id: 2, age: 2 },
    { id: 3, age: 2 },
    { id: 1, age: 1 },
]

function uniqueByKey (data, key) {
    return [...new Map(data.map(x => [x[key], x])).values()]
}

console.log(uniqueByKey(users, 'id')) // [ { id: 1, age: 1 }, { id: 2, age: 2 }, { id: 3, age: 2 } ]

function uniqueByKey2 (data, key) {
    const obj = {}
    data = data.reduce((prev, next) => {
        if (!obj[next[key]]) {
            obj[next[key]] = true
            prev.push(next)
        }
        return prev
    }, [])
    return data
}

console.log(uniqueByKey2(users, 'id')) // [ { id: 1, age: 1 }, { id: 2, age: 2 }, { id: 3, age: 2 } ]

